package com.frank.towerrush.service;

import com.frank.towerrush.util.SystemParameter;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

/**
 * 声音服务
 * 
 * @author Frank
 *
 */
public final class SoundService extends Service {
    private static SoundService service;

    private MediaPlayer player;
    // TODO 音效池

    class MyBinder extends Binder {
    }

    /**
     * 获取SoundService
     * 
     * @return SoundService的实例
     */
    public static SoundService getService() {
        if (service == null) {
            service = new SoundService();
        }
        return service;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        service = this;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    /**
     * 播放音乐
     * 
     * @param resid
     *            音乐id
     * @param looping
     *            是否循环
     */
    public void musicStart(Context context, int resid, boolean looping) {
        if (player != null && player.isPlaying()) {
            return;
        }
        player = MediaPlayer.create(context, resid);
        player.setLooping(looping);
        player.setVolume(SystemParameter.musicVolume, SystemParameter.musicVolume);
        player.start();
    }

    /**
     * 关闭音乐
     */
    public void musicStop() {
        if (player == null) {
            return;
        }
        player.stop();
        player.release();
        player = null;
    }

    /**
     * 切换音乐
     * 
     * @param resid
     *            要切换的音乐
     * @param looping
     *            是否循环
     */
    public void musicChange(Context context, int resid, boolean looping) {
        if (player != null) {
            musicStop();
        }
        musicStart(context, resid, looping);
    }

    /**
     * 调整音乐音量
     */
    public void changeVolume() {
        float volume = SystemParameter.musicVolume / 15f;
        player.setVolume(volume, volume);
    }
}
